package com.quectel.util.common;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.support.StandardTypeConverter;

import java.util.Map;

/**
 * el表达式
 *
 * @author caolu
 */
public class SpringExpressionParser {


    /**
     * 获取value
     *
     * @param params          map.put("user",new User(1))
     * @param expression      你好#{#user.id} 其他形式如#{#user.getAddress().get(0)} #{1==1?1:2}
     * @param returnClazzType String.class
     * @param <T>
     * @return 当user.id为null时结果为：你好
     */
    public static <T> T getValue(Map<String, Object> params, String expression, Class<T> returnClazzType) {
        return getValue(params, expression, true, returnClazzType);
    }

    /**
     * 获取value
     *
     * @param params          map.put("user",new User(1))
     * @param expression      你好#{#user.id} 其他形式如#{#user.getAddress().get(0)} #{1==1?1:2}
     * @param nullToEmpty     null转为为空串不显示
     * @param returnClazzType String.class
     * @param <T>
     * @return
     */
    public static <T> T getValue(Map<String, Object> params, String expression, boolean nullToEmpty, Class<T> returnClazzType) {

        StandardEvaluationContext context = new StandardEvaluationContext();

        context.setVariables(params);

        if (!nullToEmpty) {
            context.setTypeConverter(new StandardTypeConverter() {
                @Override
                public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) {
                    Object result = super.convertValue(value, sourceType, targetType);
                    return result == null ? null + "" : result;
                }
            });
        }


        ExpressionParser parser = new SpelExpressionParser();

        return parser.parseExpression(expression, new TemplateParserContext()).getValue(context, returnClazzType);
    }


}
